﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShimmerConnect
{
    class MatlabWrapper
    {
        MLApp.MLApp matlabInterface;
        string workingFolder = "C:\\Users\\jf2lin\\Documents\\MATLAB\\APARS";
        string shimmerFolder = "C:\\Users\\jf2lin\\Documents\\MATLAB\\APARS\\shimmer";

        public MatlabWrapper(ShimmerApplicationSettings pSettings)
        {
            // open link to MATLAB COM server
            matlabInterface = new MLApp.MLApp();

            FctEval("fprintf", 0, "urber\n");

            // browse to working folder
            Navigate(workingFolder);

            // set up MATLAB environment
            Eval("close all");
            Eval("clear all");
            Eval("path(path,'" + shimmerFolder + "')"); // set up path

            FctEval("shimmerInitGlobal", 0, pSettings.SerialPortConnection, pSettings.SerialPortConnectBtName); // initialize shimmer on MATLAB side

            //for (int i = 0; i < pSettings.SerialPortConnection.Length; i++)
            //{
                
            //}
        }

        public string Eval(string matlabCmd)
        {
            // calls 'eval'
            return matlabInterface.Execute(matlabCmd).Replace("\u000a".ToString(), Environment.NewLine);
        }

        public object FctEval(string matlabCmd, int outputCount, object param1)
        {
            // calls 'feval', with 1 input
            object outObj;
            matlabInterface.Feval(matlabCmd, outputCount, out outObj, param1);
            return outObj;
        }

        public object FctEval(string matlabCmd, int outputCount, object param1, object param2)
        {
            // calls 'feval', with 1 input
            object outObj;
            matlabInterface.Feval(matlabCmd, outputCount, out outObj, param1, param2);
            return outObj;
        }

        public void PutWorkspaceData(string varName, string workspaceName, object data)
        { 
            matlabInterface.PutWorkspaceData(varName, workspaceName, data);
        }

        public void Navigate(string targetFolder)
        {
            Eval("cd " + targetFolder);
        }

        public void CloseVariable()
        {
            matlabInterface.Quit();
            //Eval("exit");
        }

        ~MatlabWrapper()
        {
            CloseVariable();
        }

        //public void MatlabTestSeq()
        //{
        //    //MessageBox.Show(matlabInterface.Execute("magic(4)"));

        //    int[] dataMtx = new int[5] { 1, 2, 3, 4, 5 };
        //    int[,] myArray = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

        //    matlabInterface.PutWorkspaceData("foo", "base", dataMtx);
        //    matlabInterface.PutWorkspaceData("foo2", "base", myArray);
        //    matlabInterface.PutWorkspaceData("bar", "base", "tiger");
        //}
    }
}
